<template>
	<a-modal :visible="visible" width="550px" title="预定变更" centered destroyOnClose @cancel="cancel" :footer="null" :maskClosable="false" :bodyStyle="{padding: 0}">
		<a-form ref="formRef" :model="modelRef" :rules="formRules" class="flex-container-nomal" style="max-height: 70vh" :labelCol="{style: {width: '140px'}}" @finish="run">
			<div class="flex1 auto-y">
				<a-descriptions size="small" :contentStyle="{justifyContent: 'flex-end'}">
					<!-- /{{ sexList[detailInfo.gender] }} -->
					<a-descriptions-item label="预定人信息" :span="3">{{ detailInfo.name }}/{{ detailInfo.phone }}</a-descriptions-item>
					<a-descriptions-item label="预定房源" :span="3">{{ detailInfo.houseAddress }}</a-descriptions-item>
					<a-descriptions-item label="最晚签约日期" :span="3">{{ formatDate(detailInfo.signDate) }}</a-descriptions-item>
					<a-descriptions-item label="定金" :span="3">{{ detailInfo.money }}元</a-descriptions-item>
					<a-descriptions-item label="备注" :span="3">{{ detailInfo.comment }}</a-descriptions-item>
				</a-descriptions>
				<a-divider type="horizontal" style="background-color: #f5f5f5" />
				<a-form-item label="变更方式" name="transferType">
					<a-radio-group v-model:value="modelRef.transferType" @change="transferTypeChange">
						<a-radio :value="1">变更房间</a-radio>
						<!--  v-if="detailInfo.isPreBook" -->
						<a-radio :value="3">变更最晚签约日期</a-radio>
						<a-radio :value="2">转移人员</a-radio>
					</a-radio-group>
				</a-form-item>
				<template v-if="modelRef.transferType == 1">
					<a-form-item label="转移房间地址" name="houseId">
						<a-select :options="houseData" v-model:value="modelRef.houseId" label-in-value show-search placeholder="请输入转移房间地址" :default-active-first-option="false" :show-arrow="false" :filter-option="false" :not-found-content="null" :field-names="{label: 'address', value: 'houseRoomId'}" @search="handleSearch" @change="handleChange" />
					</a-form-item>
				</template>
				<template v-else-if="modelRef.transferType == 3">
					<a-form-item label="变更最晚签约日期" name="signDate">
						<a-date-picker v-model:value="modelRef.signDate" placeholder="请选择变更最晚签约日期" :showToday="false" :value-format="DATE_FORMAT.DATE" @change="changeTime" :disabledDate="disabledDate" :allowClear="false" />
					</a-form-item>
				</template>
				<template v-else>
					<a-form-item label="转移人姓名" name="name">
						<a-input-group compact class="display-flex">
							<a-input v-model:value="modelRef.name" placeholder="请输入转移人姓名" style="flex: 1" />
							<a-form-item-rest>
								<a-radio-group v-model:value="modelRef.gender" button-style="solid">
									<a-radio-button :value="1">男</a-radio-button>
									<a-radio-button :value="2">女</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
					<a-form-item label="转移人手机号" name="phone">
						<a-input v-model:value="modelRef.phone" :maxlength="11" placeholder="请输入转移人手机号" />
					</a-form-item>
				</template>
			</div>
			<div class="a-modal-dialog-footer">
				<a-space :size="12">
					<a-space :size="12">
						<a-button @click="cancel">取消</a-button>
						<a-button type="primary" html-type="submit" :loading="loading" :disabled="loading">确定</a-button>
					</a-space>
				</a-space>
			</div>
		</a-form>
	</a-modal>
</template>
<script setup lang="ts">
	import {reactive, ref, watch} from 'vue'
	import {useRequest} from 'vue-request'
	import {getBookDetail, bookTransfer, searchByAddress, getHouseBookRule, getRenterContractDetail} from '@/api/contract'
	import {message, Modal} from 'ant-design-vue'
	import {sexList} from '@/utils'
	import {checkPhone} from '@/utils/check'
	import type {Rule} from 'ant-design-vue/es/form'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import dayjs from 'dayjs'

	const props = defineProps({
		visible: {
			type: Boolean,
			required: true
		},
		id: {
			type: [String, Number],
			default: ''
		}
	})
	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		emit('update:visible', false)
		resetForm()
	}
	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				getDetail()
				getHouseBookRuleConfig()
			}
		}
	)

	const houseBookRuleConfig = ref<any>()
	const preBookDays = ref(0)
	const getHouseBookRuleConfig = () => {
		getHouseBookRule().then(res => {
			// 添加一个默认值
			const data = res.data
				? res.data
				: {
						day: 1, // 默认为1
						preBookDays: 0
				  }
			if (!res.data) {
				Modal.warning({
					title: () => '提示',
					content: () => '预定规则未配置，还请配置完预定规则再操作！'
				})
			}
			houseBookRuleConfig.value = data
			preBookDays.value = data?.day
		})
	}
	const contractDetail = ref<any>(null)
	const getContractDetail = (id = '') => {
		if (!id) return
		getRenterContractDetail(id).then(res => {
			contractDetail.value = res.data
		})
	}

	const modelRef = reactive({
		houseId: null,
		housePid: '',
		name: '',
		phone: '',
		transferType: 1,
		gender: 1,
		signDate: null
		// isPreBook: null
	})

	const disabledDate = (currentDate: any) => {
		// 最小时间和最大时间分别加一天 因为不包括合同结束当天的时间
		/**  不包括当天(待产品确定是否包括当天)
			const diff = dayjs(dayjs().format('YYYY-MM-DD')).diff(contractDetail.value?.endTime, 'day')
			const endTime = diff >= 0 ? dayjs().add(1, 'day').format(DATE_FORMAT.DATE) : contractDetail.value?.endTime
			const maxDate = dayjs(endTime).add(1, 'day').add(houseBookRuleConfig.value.day, 'day').format(DATE_FORMAT.DATE)
			return maxDate ? dayjs(endTime).add(1, 'day').isAfter(currentDate, 'day') || currentDate > new Date(maxDate) : dayjs(endTime).isAfter(currentDate, 'day')
 		*/
		// 包括当天
		const diff = dayjs(dayjs().format('YYYY-MM-DD')).diff(contractDetail.value?.endTime, 'day')
		const endTime = diff >= 0 ? dayjs().add(1, 'day').format(DATE_FORMAT.DATE) : contractDetail.value?.endTime
		const maxDate = dayjs(endTime).add(houseBookRuleConfig.value.day, 'day').format(DATE_FORMAT.DATE)
		return maxDate ? dayjs(endTime).isAfter(currentDate, 'day') || currentDate > new Date(maxDate) : dayjs(endTime).isAfter(currentDate, 'day')
	}

	const changeTime = () => {
		// date时间选择组件有bug change完之后需要把日期减去1
		houseBookRuleConfig.value.day = preBookDays.value - 1
	}

	const formRules = {
		transferType: [
			{
				required: true,
				message: '请选择转移方式'
			}
		],
		houseId: [
			{
				required: true,
				message: '请选择转移房间地址'
			}
		],
		name: [
			{
				required: true,
				message: '请输入转移人姓名'
			}
		],
		phone: [
			{
				required: true,
				validator: async (_rule: Rule, value: string) => {
					if (!value) {
						return Promise.reject('请输入手机号')
					} else if (!checkPhone.test(value)) {
						return Promise.reject('手机号格式不正确')
					} else {
						return Promise.resolve()
					}
				}
			}
		],
		signDate: [
			{
				required: true,
				message: '请选择变更最晚签约日期'
			}
		]
	}

	const detailInfo = ref<any>({})
	const getDetail = () => {
		getBookDetail(props.id).then((res: any) => {
			detailInfo.value = res.data
			getContractDetail(res.data.preContractId)
		})
	}

	const sendRequest = () => {
		return bookTransfer({
			...modelRef,
			id: props.id
		})
	}

	const {run, loading} = useRequest(sendRequest, {
		manual: true,
		formatResult: (res: any) => {
			if (res.code == 200) {
				message.success('操作成功')
				setTimeout(() => {
					emit('success')
					cancel()
				}, 300)
			}
		}
	})

	let timeout: any
	const houseData = ref<any>([])
	const handleSearch = (val: any) => {
		if (timeout) {
			clearTimeout(timeout)
			timeout = null
		}
		let params = {
			houseType: 0,
			like: val,
			current: 1,
			/** 1.租客合同；2.业主合同；3.房源预定；4.工单 */
			bizType: 3,
			preBookDays: houseBookRuleConfig.value.preBookDays,
			size: 9999,
			statusInCondition: [11]
		}
		const fake = () => {
			searchByAddress(params).then((res: any) => {
				houseData.value = res.data.records
			})
		}
		timeout = setTimeout(fake, 300)
	}
	const handleChange = (val: any) => {
		modelRef.houseId = val ? val.value : ''
		modelRef.housePid = val ? val.option.houseBaseId : ''
		if (!val) {
			houseData.value = []
		}
	}

	const transferTypeChange = (e: any) => {
		console.log(e.target.value)
		if (e.target.value == 1) {
			modelRef.name = ''
			modelRef.phone = ''
		} else {
			houseData.value = []
			modelRef.houseId = null
			modelRef.housePid = ''
		}
	}

	// 重置表单
	const formRef = ref<any>()
	const resetForm = () => {
		detailInfo.value = {}
		modelRef.housePid = ''
		modelRef.gender = 1
		formRef.value.resetFields()
	}
</script>
